import React, { Component,Fragment } from 'react'
import {Link,withRouter} from 'react-router-dom'
import {  Menu } from 'antd';
import {
    TagOutlined
} from '@ant-design/icons';
const { SubMenu } = Menu;

class AsideMenu extends Component {
    constructor(props) {
        super(props);
        this.state= {
            selectedKeys:[],   //selectedKeys 当前选中的菜单项 key 数组
            openKeys:[],   //openKeys, 当前展开的 SubMenu 菜单项 key 数组
            menus:this.props.menus
        }
    }
    componentDidMount(){
        const pathname = this.props.location.pathname;
        const menukey = pathname.split("/").slice(0,3).join('/');
        const menuHigh = {
            selectedKeys: pathname,
            openKeys: menukey
        }
        this.selectMenuHigh(menuHigh)
    }
    selectMenu =({item,key,keyPath}) => {
        // 选中菜单
        const menuHigh = {
            selectedKeys: key,
            openKeys: keyPath[keyPath.length - 1]
        }
        this.selectMenuHigh(menuHigh)
    }
    openMenu = (openKeys) => {
        // 展开
        this.setState({
            openKeys: [openKeys[openKeys.length - 1]]
        })
    }
    selectMenuHigh = ({selectedKeys,openKeys}) => {
        // 菜单高亮
        this.setState({
            selectedKeys: [selectedKeys],
            openKeys: [openKeys]
        })
    }
    // 处理一级菜单栏
    renderMenu =({title,key,path, text}) => {
        return (
            <Menu.Item key={key}  icon={<TagOutlined/>}>
                <Link to={path}>
                    <span>{text}</span>
                </Link>
            </Menu.Item>
        )
    }
    // 处理子级菜单栏
    renderSubMnenu = ({text,key,children}) => {
        return (
            <SubMenu key={key} title={text}>
                {
                    children && children.map(item => {
                        return item.children && item.children.length > 0 ? this.renderSubMnenu(item) : this.renderMenu(item)
                    })
                }
            </SubMenu>
        )

    }
    render() {

        let Router2= this.props.menus || [];
        const { selectedKeys,openKeys } = this.state
        //debugger
        return (
            <Fragment>
                <Menu
                    onOpenChange={this.openMenu}
                    onClick={this.selectMenu}
                    theme="dark"
                    mode="inline"
                    selectedKeys={selectedKeys}
                    openKeys={openKeys}
                    style={{ height: '100%', borderRight: 0 }}
                >
                    {
                        Router2 && Router2.map(firstItem => {
                            return firstItem.children && firstItem.children.length > 0 ? this.renderSubMnenu(firstItem) : this.renderMenu(firstItem)
                        })
                    }
                </Menu>
            </Fragment>
        )
    }
}
export default withRouter(AsideMenu)
